import json
import uuid
from datetime import datetime
from celery import shared_task
from  celery.result import AsyncResult
from Model.default import get_db
from Model.mysocketio.info import Request_Room, Group_Room, Group_Room_Expand, Double_Room
from Model.user.User import user_expand
from api.mysocketio.create_Room import deal_create_double_room, deal_user_friends_info_double, \
    deal_user_friends_info_group
from api.mysocketio.update_room_info import update_userinfo_to_room
from celerywork.mycelery import celery_app



@shared_task(soft_time_limit=8,name="request_create_room")
def deal_create_request_rooms(ids,type,room_id,request_id):
    try:
        db=get_db()
        now = str(datetime.now())

        if type=='double':
            middle_room=Request_Room(room_id=room_id,one=ids[0],another=ids[1]
                              ,room_type='double',created_at=now,user_id=request_id)

        if type=='group':
            middle_room = Request_Room(room_id=room_id,
                                room_type='group',
                                user_id=request_id,
                                )
        db.add(middle_room)
        db.commit()
        id=middle_room.room_id
        # 仅仅存储room_id为了使用过期效果
        return  id
    except Exception as e:
        db.rollback()

    finally:
        db.close()

def deal_create_request_room(ids,type,user_id,room_id=str(uuid.uuid4())):
    try:
        #注意由于序列化到text类型会导致user_id转为str
        #      0申请中,1成功,-1拒绝 2过期或不存在
        db=get_db()

        result=celery_app.send_task("request_create_room", args=(ids, type,room_id,user_id), expires=60 * 60 * 24 * 7,
                             time_limit=60 * 0.5)
        # if not result.ready():
        #     return False

        if type == 'double':
            # 处理请求关系信息
            user_id_ep1 = db.query(user_expand).filter_by(id=user_id).first()
            user_id_ep2 = db.query(user_expand).filter_by(id=ids[1]).first()

            middle_data1 = json.loads(user_id_ep1.request_room or json.dumps({}))
            middle_data2 = json.loads(user_id_ep2.request_room or json.dumps({}))

            # 对于处理采用处理时,对redis存储的信息处理,来判断是否过期,只有当被处理时才检测
            if user_id == ids[0]:
                # 0是申请者
                middle_data1[room_id] = {'room_id': room_id,
                                         'type': 'request', 'status': 0,
                                         'room_type': 'double',
                                         'id':result.id
                                         }

                middle_data2[room_id] = {'room_id': room_id,
                                         'type': 'response', 'status': 0,
                                         'room_type': 'double',
                                         'id':result.id
                                        }
            else:
                # 1是申请者
                middle_data1[room_id] = {'room_id': room_id,
                                         'type': 'response', 'status': 0,
                                         'room_type': 'double',
                                         'id': result.id
                                         }
                middle_data2[room_id] = {'room_id': room_id,
                                         'type': 'request', 'status': 0,
                                         'room_type': 'double',
                                         'id': result.id
                                         }

            user_id_ep1.request_room = json.dumps(middle_data1)

            user_id_ep2.request_room = json.dumps(middle_data2)
        elif type == 'group':
            # 如果是群组存储到群组里,用于权限判定,不使用放到created
            group_info = db.query(Group_Room_Expand).filter_by(room_id=room_id).first()
            user_id_ep=db.query(user_expand).filter_by(id=user_id).first()
            middle_data=json.loads(user_id_ep.request_room or json.dumps({}))
            middle_data[room_id]={'room_id': room_id,
                                  'type': 'request', 'status': 0,
                                  'room_type': 'group',
                                  'id': result.id
                                  }
            if not group_info:
                group_info = Group_Room_Expand(id=room_id,room_id=room_id)
                db.add(group_info)
            middle_data = json.loads(group_info.request_info or json.dumps({}))

            middle_data[user_id] = {'status': 0,'id': result.id}
            group_info.request_info=json.dumps(middle_data)
        db.commit()

        return  True
    except Exception as e:
        print(e)
        return  False
    finally:
        db.close()


async  def deal_response_request_room(room_id,deal,user_id):
    try:

        db = get_db()
        userexpand = db.query(user_expand).filter_by(id=user_id).first()
        now = str(datetime.now())
        if not userexpand:
            return -1

        middle_room = db.query(Request_Room).filter_by(room_id=room_id).first()
        user_requestrooms = json.loads(userexpand.request_room or '{}')
        middle_room.status = deal

        if user_requestrooms:
            result = AsyncResult(id=user_requestrooms.get(room_id, {}).get('id'), app=celery_app)
            if result.status == 'REVOKED':
                user_requestrooms[room_id]['status'] =2
                userexpand.request_room = json.dumps(user_requestrooms)
                middle_room.status = 2
                db.commit()
                return 2

            if middle_room.room_type == 'double':
                if deal == 1:
                    doubleroom = Double_Room(
                        room_id=middle_room.room_id,
                        created_at=str(datetime.now()),
                        one=middle_room.one,
                        another=middle_room.another
                    )
                    if (update_userinfo_to_room(room_id, middle_room.one, 'joined_at', now, 'double') and
                            update_userinfo_to_room(room_id, middle_room.another, 'joined_at', now, 'double') and
                            deal_user_friends_info_double(db, [middle_room.one, middle_room.another])):
                        db.add(doubleroom)
                        db.commit()
                        return 1
                    return 0
                else:
                    user_requestrooms[room_id]['status'] = deal
                    userexpand.request_room = json.dumps(user_requestrooms)
                    db.commit()
                    return 1

            elif middle_room.room_type == 'group':
                group_expandinfo = db.query(Group_Room_Expand).filter_by(room_id=middle_room.room_id).first()
                middle_info = json.loads(group_expandinfo.request_info or '{}')
                middle_info[room_id]['status'] = deal
                group_expandinfo.request_info = json.dumps(middle_info)
                user_requestrooms[room_id]['status'] = deal
                userexpand.request_room = json.dumps(user_requestrooms)

                if deal == 1:
                    if (deal_user_friends_info_group(db, [middle_room.user_id]) and
                            update_userinfo_to_room(room_id, middle_room.user_id, 'joined_at', now, 'group', db)):
                        db.commit()
                        return 1
                    return 0
        return 0
    except Exception as e:
        print('aaaa')
        print(e)
        db.rollback()
        raise
    finally:
        db.close()

